package com.topc.base.utils;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EasyExcelUtils {

    public void noModelWrite(String fileName, List<List<Object>> data, List<String> headers, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String downFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + downFileName + ".xlsx");
            // 这里需要设置不关闭流
            List<List<String>> h = new ArrayList<>();
            headers.forEach(header->{
                List<String> t=new ArrayList<>();
                t.add(header);
                h.add(t);
            });
            EasyExcel.write(response.getOutputStream()).autoCloseStream(Boolean.FALSE).head(h).sheet(fileName).doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(map);
        }
    }

}
